import 'package:dio/dio.dart';

class Api {
  var baseUrl = 'http://test-service.ryzsz.com/';

  final dio = Dio();

  static Map<String, dynamic> headers = {};

  void initHeader(Map<String, dynamic> data) {
    headers = data;
  }

  // get 请求
  Future<dynamic> get(String url, Map<String, dynamic>? param) async {
    String path = baseUrl + url;
    print(path);
    print('param:$param');
    try {
      Response response;
      response = await dio.get(
        path,
        queryParameters: param,
        options: Options(headers: headers),
      );
      print(response);
      if (response.statusCode == 200) {
        var res = response.data as Map<String, dynamic>;
        return res['data'] as Map<String, dynamic>;
      } else {
        return null;
      }
    } on DioException catch (e) {
      // 处理不同类型的Dio异常
      dioError(e);
      return null;
    }
  }

  // post 请求
  Future<dynamic> post(String url, Map<String, dynamic>? param) async {
    String path = baseUrl + url;
    print(path);
    print('param:$param');
    try {
      Response response;
      response = await dio.post(
        path,
        queryParameters: param,
        options: Options(headers: headers),
      );
      print(response);
      if (response.statusCode == 200) {
        var res = response.data as Map<String, dynamic>;
        return res['data'] as Map<String, dynamic>;
      } else {
        return null;
      }
    } on DioException catch (e) {
      // 处理不同类型的Dio异常
      dioError(e);
      return null;
    }
  }

  void dioError(DioException e) {
    switch (e.type) {
      case DioExceptionType.badResponse:
        print('服务器响应错误: ${e.response?.statusCode}');
        break;
      case DioExceptionType.connectionTimeout:
        print('连接超时');
        break;
      case DioExceptionType.sendTimeout:
        print('发送超时');
        break;
      case DioExceptionType.receiveTimeout:
        print('接收超时');
        break;
      default:
        print('其他错误: ${e.message}');
    }
  }
}
